package com.situ.student.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.omg.PortableServer.ID_ASSIGNMENT_POLICY_ID;

import com.situ.student.entity.Banji;
import com.situ.student.entity.PageBean;
import com.situ.student.entity.Student;
import com.situ.student.entity.StudentSearchCondition;
import com.situ.student.entity.User;
import com.situ.student.service.IBanjiService;
import com.situ.student.service.IStudentService;
import com.situ.student.service.impl.BanjiServiceImpl;
import com.situ.student.service.impl.StudentServiceImpl;

import net.sf.json.JSONObject;

public class StudentController extends HttpServlet{
	private IStudentService studentService = new StudentServiceImpl();
	private IBanjiService banjiService = new BanjiServiceImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("StudentController.service()");
		// http://localhost:8080/Java1807Web/student?method=list
		System.out.println(req.getContextPath());//  /Java1807Web
		System.out.println(req.getServletPath());//  /student
		System.out.println(req.getRequestURI());//	 /Java1807Web/student
		System.out.println(req.getRequestURL());//   http://localhost:8080/Java1807Web/student
		
		//判断用户有没有登录
		/*HttpSession session = req.getSession();
		User user = (User) session.getAttribute("user");
		if (user == null) {
			//用户没有登录，重定向到登录界面
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
			return;
		}*/
		
		//post请求乱码问题，放在service方法最上面
		req.setCharacterEncoding("utf-8");
		String method = req.getParameter("method");
		switch (method) {
		case "list":
			list(req, resp);
			break;
		case "pageList":
			pageList(req, resp);
			break;
		case "deleteById":
			deleteById(req, resp);
			break;
		case "insert":
			insert(req, resp);
			break;
		case "toUpdate":
			toUpdate(req, resp);
			break;
		case "update":
			update(req, resp);
			break;
		case "deleteAll":
			deleteAll(req, resp);
			break;
		case "checkName":
			checkName(req, resp);
			break;
		case "getAddPage":
			getAddPage(req, resp);
		default:
			break;
		}
	}

	//通过访问这个Servlet，查出所有班级信息，放到域对象中，转发到student_add.jsp
	private void getAddPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<Banji> list = banjiService.list();
		req.setAttribute("list", list);
		req.getRequestDispatcher("/student_add.jsp").forward(req, resp);
	}

	private void checkName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String name = req.getParameter("name");
		boolean isExist = studentService.checkName(name);
		// {"isExist":isExist}
		Map<String, Object> map = new HashMap<>();
		map.put("isExist", isExist);
		JSONObject jsonObject = JSONObject.fromObject(map);
		resp.setContentType("text/html;charset=utf-8");
		//resp.getWriter().write("{\"isExist\":"+isExist+"}");
		resp.getWriter().write(jsonObject.toString());
	}

	private void deleteAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String[] selectIds = req.getParameterValues("selectIds");
		System.out.println(Arrays.toString(selectIds));
		studentService.deleteAll(selectIds);
		resp.sendRedirect(req.getContextPath() + "/student?method=pageList");
	}

	private void pageList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// http://localhost:8080/Java1807Web/student?method=pageList&pageNo=2&pageSize=3
		//1、接收请求参数
		String pageNoStr = req.getParameter("pageNo");
		if (pageNoStr == null || pageNoStr.equals("")) {
			pageNoStr = "1";
		}
		int pageNo = Integer.parseInt(pageNoStr);
		String pageSizeStr = req.getParameter("pageSize");
		if (pageSizeStr == null || pageSizeStr.equals("")) {
			pageSizeStr = "3";
		}
		int pageSize = Integer.parseInt(pageSizeStr);
		String name = req.getParameter("name");
		String ageStr = req.getParameter("age");
		Integer age = null;
		if (ageStr != null && !"".equals(ageStr)) {
			age = Integer.parseInt(ageStr);
		}
		String gender = req.getParameter("gender");
		//把所有的搜索条件封装成了StudentSearchCondition这样一个对象
		StudentSearchCondition searchCondition = new StudentSearchCondition(pageNo, pageSize, name, age, gender);
		//2、封装成PageBean，调用Service层业务逻辑
		//List<Student> list; 
		//PageBean<Student> pageBean = studentService.getPageBean(pageNo, pageSize);
		PageBean pageBean = studentService.getPageBean(searchCondition);
		System.out.println(pageBean);
		//3、控制界面跳转
		req.setAttribute("pageBean", pageBean);
		req.setAttribute("searchCondition", searchCondition);
		req.getRequestDispatcher("student_list.jsp").forward(req, resp);
	}

	private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		//1、得到浏览器传递过来的参数信息
		Integer id = Integer.parseInt(req.getParameter("id"));
		String name = req.getParameter("name");
		Integer age = Integer.parseInt(req.getParameter("age"));
		String gender = req.getParameter("gender");
		Student student = new Student(id, name, age, gender);
		//2、调用service处理
		boolean result = studentService.update(student);
		System.out.println(result ? "成功" : "失败");
		//3、转发或者重定向到列表界面
		resp.sendRedirect(req.getContextPath() + "/student?method=list");
	}

	private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//根据id查找出要修改的学生对象
		Integer id = Integer.parseInt(req.getParameter("id"));
		Student student = studentService.findById(id);
		List<Banji> list = banjiService.list();
		//转发到student_update.jsp页面
		req.setAttribute("student", student);
		req.setAttribute("list", list);
		req.getRequestDispatcher("/student_update.jsp").forward(req, resp);
	}

	public void insert(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		//1、得到浏览器传递过来的参数信息
		String name = req.getParameter("name");
		Integer age = Integer.parseInt(req.getParameter("age"));
		String gender = req.getParameter("gender");
		Integer banjiId =Integer.parseInt(req.getParameter("banjiId"));
		Student student = new Student(name, age, gender, banjiId);
		//2、调用service处理
		boolean result = studentService.insert(student);
		System.out.println(result ? "成功" : "失败");
		//3、转发或者重定向到列表界面
		resp.sendRedirect(req.getContextPath() + "/student?method=pageList");
	}

	public void deleteById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1、得到浏览器传递过来的参数信息
		Integer id = Integer.parseInt(req.getParameter("id"));
		//2、调用service处理
		boolean result = studentService.deleteById(id);
		System.out.println(result ? "成功" : "失败");
		//3、重定向到列表界面
		resp.sendRedirect(req.getContextPath() + "/student?method=list");
		
		//转发
		//req.getRequestDispatcher("/findStudent").forward(req, resp);
	}

	public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1、得到浏览器传递过来的参数信息
		String name = req.getParameter("name");
		List<Student> list = new ArrayList<>();
		if (name == null || name.equals("")) {//查找所有
			list = studentService.list();
		} else {//根据名字模糊查找
			//模糊查找
			//List<Student> list = studentService.findByName(name);
			list = new ArrayList<>();
			Student student = new Student(22, name + " Java1807", 30, "男");
			list.add(student);
		}
		req.setAttribute("list", list);
		
		for (Student student : list) {
			System.out.println(student);
		}
		//将list放到req里面
		req.setAttribute("list", list);
		//转发到student_list.jsp页面进行展示
		req.getRequestDispatcher("/student_list.jsp").forward(req, resp);
	}
}
